package com.anjoyo.xgh.musicshare.api;

import java.util.ArrayList;
import java.util.List;

import com.anjoyo.xgh.musicshare.util.BitmapUtil;

import android.graphics.Bitmap;
import android.os.Handler;
import android.os.Message;
import android.support.v4.util.LruCache;

public class AsynImageload {
	// 创建任务对象类集合
	public List<ImgTask> tasks;
	// 用于缓存已经下载的bitmap对象，内存缓存
	public LruCache<String, Bitmap> cache;
	// 下载线程
	ImageDownloadThread thread;
	boolean isload = false; 
	
	public AsynImageload() {
		tasks = new ArrayList<AsynImageload.ImgTask>();
		cache = new LruCache<String, Bitmap>(80);
		thread = new ImageDownloadThread();
		thread.start();
	}

	class ImageDownloadThread extends Thread {
		@Override
		public void run() {
			super.run();
			while (true) {
				while (tasks.size()>0) {
					isload = true;
					ImgTask imgTask = tasks.remove(0);
					Bitmap bitmap = BitmapUtil.getUserIcon(imgTask.url);
					if (bitmap!=null) {
//						System.out.println("加入到缓存");
							cache.put(imgTask.url, bitmap);
					}
					imgTask.bitmap = bitmap;
					Message message = new Message();
					message.what = 0;
					message.obj = imgTask;
					handler.sendMessage(message);
				}
				synchronized (this) {
					try {
						isload = false;
						this.wait();
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			}
		}
	}

	Handler handler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			ImgTask imgTask = (ImgTask) msg.obj;
			imgTask.callback.loadImage(imgTask.bitmap, imgTask.url);
		}
	};

	public Bitmap loadImageview(String url, ImageCallback callback) {
		Bitmap bitmap = null;
		if (cache.get(url) != null) {
//			System.out.println("缓存有");
			return cache.get(url);
		} else {
//			System.out.println("缓存无");
			ImgTask imgTask = new ImgTask();
			imgTask.url = url;
			imgTask.callback = callback;
			tasks.add(imgTask);
			if (!isload) {
				synchronized (thread) {
					thread.notify();
				}
			}
		}
		return bitmap;
	}

	class ImgTask {
		public String url;
		public Bitmap bitmap;
		ImageCallback callback;
	}

	public interface ImageCallback {
		void loadImage(Bitmap bitmap, String url);
	}

}
